<template>
  <div class="border border-solid border-gray-100 h-full z-10">
    <Toolbar
      :editor="editorRef"
      :default-config="toolbarConfig"
      mode="default"
    />
    <Editor
      v-model="valueHtml"
      class="overflow-y-hidden mt-0.5"
      style="height: 20rem"
      :default-config="editorConfig"
      mode="default"
      @onCreated="handleCreated"
      @onChange="change"
    />
  </div>
</template>

<script setup>
  import '@wangeditor/editor/dist/css/style.css' // 引入 css

  const basePath = import.meta.env.VITE_BASE_API

  import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

  import { ElMessage } from 'element-plus'
  import { getUrl } from '@/utils/image'
  import { useUserStore } from '@/pinia/modules/user'

  const emits = defineEmits(['change', 'update:modelValue'])
  const userStore = useUserStore()

  const change = (editor) => {
    emits('change', editor)
    emits('update:modelValue', valueHtml.value)
  }

  const props = defineProps({
    modelValue: {
      type: String,
      default: ''
    }
  })

  const editorRef = shallowRef()
  const valueHtml = ref('')

  const toolbarConfig = {
    toolbarKeys: [
      'headerSelect',
      'blockquote',
      '|',
      'bold',
      'underline',
      'italic',
      'through',
      'code',
      'sup',
      'sub',
      'clearStyle',
      '|',
      'color',
      'bgColor',
      '|',
      'fontSize',
      'fontFamily',
      'lineHeight',
      '|',
      'bulletedList',
      'numberedList',
      'todo',
      '|',
      'emotion',
      'insertLink',
      'uploadImage',
      'uploadVideo',
      'insertTable',
      'codeBlock',
      'divider',
      '|',
      'undo',
      'redo',
      '|',
      'fullScreen'
    ]
  }
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {}
  }
  editorConfig.MENU_CONF['uploadImage'] = {
    fieldName: 'file',
    server: basePath + '/fileUploadAndDownload/upload?noSave=1',
    headers: {
      'x-token': userStore.token
    },
    maxFileSize: 10 * 1024 * 1024, // 10M
    allowedFileTypes: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'],
    onBeforeUpload(file) {
      console.log('Image upload before upload:', file)
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        ElMessage.error('图片文件大小不能超过10MB！')
        return false
      }
      return true
    },
    onProgress(progress) {
      console.log('Image upload progress:', progress)
    },
    onSuccess(file, res) {
      console.log('Image upload success:', file, res)
    },
    onFailed(file, res) {
      console.log('Image upload failed:', file, res)
      ElMessage.error('图片上传失败：' + (res.msg || '未知错误'))
    },
    onError(file, err, res) {
      console.log('Image upload error:', file, err, res)
      ElMessage.error('图片上传出错：' + (err.message || '网络错误'))
    },
    customInsert(res, insertFn) {
      console.log('Rich editor image upload response:', res)
      if (res.code === 0) {
        const urlPath = getUrl(res.data.file.url)
        insertFn(urlPath, res.data.file.name)
        ElMessage.success('图片上传成功')
        return
      }
      console.error('Image upload failed:', res)
      ElMessage.error(res.msg || '图片上传失败')
    }
  }

  // 配置视频上传
  editorConfig.MENU_CONF['uploadVideo'] = {
    fieldName: 'file',
    server: basePath + '/fileUploadAndDownload/upload?noSave=1',
    headers: {
      'x-token': userStore.token
    },
    maxFileSize: 50 * 1024 * 1024, // 50M
    maxNumberOfFiles: 3,
    allowedFileTypes: ['video/*'],
    onBeforeUpload(file) {
      console.log('Video upload - onBeforeUpload:', file)
      console.log('File object type:', typeof file)
      console.log('File object keys:', Object.keys(file || {}))
      console.log('File details:', {
        name: file?.name,
        type: file?.type,
        size: file?.size
      })
      
      // 基本文件对象检查
      if (!file) {
        console.error('File object is null or undefined:', file)
        ElMessage.error('无效的文件对象')
        return false
      }
      
      // 检查文件大小（如果有的话）
      const fileSize = file.size || file.fileSize || 0
      if (fileSize > 0) {
        const fileSizeMB = (fileSize / 1024 / 1024).toFixed(2)
        const isLt50M = fileSize / 1024 / 1024 < 50
        if (!isLt50M) {
          console.error('File too large:', fileSizeMB, 'MB')
          ElMessage.error(`视频文件过大！当前文件大小：${fileSizeMB}MB，最大支持：50MB`)
          return false
        }
      }
      
      // 使用文件类型检查（如果有的话）
      const fileType = file.type || file.mimeType || ''
      if (fileType && fileType.startsWith('video/')) {
        console.log('Video type validation passed via MIME type:', fileType)
        return true
      }
      
      // 如果有文件名，使用扩展名检查
      const fileName = file.name || file.fileName || file.originalName || ''
      if (fileName) {
        const videoTypeList = ['mp4', 'avi', 'rmvb', 'rm', 'asf', 'divx', 'mpg', 'mpeg', 'mpe', 'wmv', 'mkv', 'vob']
        const lowerFileName = fileName.toLowerCase()
        const isVideo = videoTypeList.some(ext => lowerFileName.endsWith('.' + ext))
        
        if (isVideo) {
          console.log('Video validation passed via file extension')
          return true
        } else {
          console.error('File type validation failed:', {
            fileName: lowerFileName,
            fileType: fileType,
            supportedTypes: videoTypeList
          })
          ElMessage.error('当前类型不支持使用，请上传视频文件！')
          return false
        }
      }
      
      // 如果没有文件类型和文件名信息，允许上传（让服务器端验证）
      console.log('No file type or name info available, allowing upload for server-side validation')
      return true
    },
    onProgress(progress) {
      console.log('Video upload progress:', progress)
    },
    onSuccess(file, res) {
      console.log('Video upload success:', file, res)
    },
    onFailed(file, res) {
      console.log('Video upload failed:', file, res)
      let errorMsg = '视频上传失败'
      
      // 根据响应信息提供具体错误原因
      if (res && res.msg) {
        errorMsg = res.msg
      } else if (res && res.message) {
        errorMsg = res.message
      } else if (res && res.error) {
        errorMsg = res.error
      }
      
      ElMessage.error(errorMsg)
    },
    onError(file, err, res) {
      console.log('Video upload error:', file, err, res)
      let errorMsg = '视频上传出错'
      
      // 根据错误类型提供具体错误信息
      if (err && err.message) {
        // 检查是否是文件大小相关错误
        if (err.message.includes('size') || err.message.includes('large') || err.message.includes('exceed')) {
          errorMsg = '视频文件过大，请选择小于50MB的视频文件'
        } else if (err.message.includes('network') || err.message.includes('timeout')) {
          errorMsg = '网络连接超时，请检查网络后重试'
        } else if (err.message.includes('format') || err.message.includes('type')) {
          errorMsg = '视频格式不支持，请上传MP4、AVI等常见格式'
        } else {
          errorMsg = '视频上传出错：' + err.message
        }
      } else if (res && res.msg) {
        errorMsg = res.msg
      } else if (res && res.message) {
        errorMsg = res.message
      }
      
      ElMessage.error(errorMsg)
    },
    customInsert(res, insertFn) {
      console.log('Video upload - customInsert:', res)
      if (res.code === 0) {
        const videoUrl = res.data.file.url
        insertFn(videoUrl)
        ElMessage.success('视频上传成功')
      } else {
        ElMessage.error('视频上传失败: ' + res.msg)
      }
    }
  }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })

  const handleCreated = (editor) => {
    editorRef.value = editor
    valueHtml.value = props.modelValue
  }

  watch(
    () => props.modelValue,
    () => {
      valueHtml.value = props.modelValue
    }
  )
</script>

<style scoped lang="scss">

</style>
